package com.tian.service.impl;

import com.alibaba.nacos.api.utils.StringUtils;
import com.tian.dto.AuthLoginDto;
import com.tian.entity.ChargeUser;
import com.tian.enums.LoginTypeEnum;
import com.tian.exception.BusinessException;
import com.tian.exception.ValidException;
import com.tian.mapper.ChargeUserMapper;
import com.tian.service.AbstractLoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;

/**
 * {@code @description:}  用户名+密码登录
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-04-07 16:42
 * {@code @version:} 1.0
 */
@Slf4j
@Service
public class NormalLoginProcessorService extends AbstractLoginService {

    @Resource
    ChargeUserMapper chargeUserMapper;

    @Override
    public int getLoginType() {
        return LoginTypeEnum.NORMAL.getCode();
    }

    @Override
    public void validate(AuthLoginDto authLoginDto) {
        if (StringUtils.isBlank(authLoginDto.getUsername()) || StringUtils.isBlank(authLoginDto.getPassword())) {
            throw new ValidException("帐号或者密码不能为空");
        }
    }

    @Override
    public ChargeUser doProcessor(AuthLoginDto authLoginDto) {
        log.info("begin NormalLoginProcessor.doProcessor:" + authLoginDto);
        ChargeUser chargeUser = chargeUserMapper.selectByName(authLoginDto.getUsername());
        if (chargeUser == null) {
            throw new BusinessException("用户名或者密码错误");
        }
        if (!DigestUtils.md5DigestAsHex(authLoginDto.getPassword().getBytes()).equals(chargeUser.getPassword())) {
            throw new BusinessException("用户名或者密码错误");
        }
        return chargeUser;
    }
}
